package cog.support.springmvc.hashmap;

import cog.support.springmvc.session.ISession;
import cog.support.springmvc.session.ISessionPool;

import java.util.HashMap;
import java.util.Map;

/**
 * 使用HashMap实现的Session池
 * 
 * @author 陈杰
 * @time 2016年9月12日 03:35:34
 * @version v0.1
 * 
 * Copyright DongHui(chenjie_java@aliyun.com)
 */
public class HashMapSessionPool implements ISessionPool {
 
	public static Map<String,ISession> sessionMap = new HashMap<String,ISession>();
	

	public ISession getSession(String tokenId) {
		return sessionMap.get(tokenId);
	}

	public ISession pollSession(String tokenId) {
		return sessionMap.remove(tokenId);
	}

    @Override
    public String createSession(String key, Object... value) {
        String[] keyArray = key.split(",");
        ISession session = this.createSession();
        for(int i = 0 ;i<keyArray.length;i++){
            session.addParameter(keyArray[i],value[i]);
        }
        sessionMap.put(session.getSessionId(),session);
        return session.getSessionId();
    }

    @Override
    public ISession createSession() {
        return new HashMapSession();
    }

    @Override
    public ISession getOrCreateSession(String tokenId) {
        ISession session = this.getSession(tokenId);
        if(session == null ){
            session = this.createSession();
            session.setSessionId(tokenId);
            sessionMap.put(tokenId,session);
        }
        return session;
    }


}
